/**
 * 
 */
package modelo.dao.jpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import modelo.bean.LatLng;

/**
 * @author Daniel Rodrigues
 * 
 */
public class JPALatLngDAO {
	private static EntityManagerFactory factory;

	public JPALatLngDAO() {
		factory = JPAFactory.getInstanceManagerFactory();
	}

	public boolean insert(LatLng ponto) {
		EntityManager em = factory.createEntityManager();
		boolean conseguiuInserir = true;
		try {
			em.getTransaction().begin();
			em.persist(ponto);
			em.getTransaction().commit();
		} catch (Exception e) {
			System.err.println(e.getMessage());
			conseguiuInserir = false;
		} finally {
			em.close();
		}
		return conseguiuInserir;
	}

	public boolean update(LatLng ponto) {
		EntityManager em = factory.createEntityManager();
		boolean conseguiuAtualizar = true;
		try {
			em.getTransaction().begin();
			em.merge(ponto);
			em.getTransaction().commit();
		} catch (Exception e) {
			System.err.println(e.getMessage());
			conseguiuAtualizar = false;
		} finally {
			em.close();
		}
		return conseguiuAtualizar;
	}

	public boolean delete(LatLng ponto) {
		EntityManager em = factory.createEntityManager();
		boolean conseguiuDeletar = true;
		try {
			em.remove(ponto);
		} catch (Exception e) {
			System.err.println(e.getMessage());
			conseguiuDeletar = false;
		} finally {
			em.close();
		}
		return conseguiuDeletar;
	}

	public LatLng consultaLatLng(LatLng ponto) {
		EntityManager em = factory.createEntityManager();
		LatLng u = new LatLng();
		try {
			u = (LatLng) em.find(LatLng.class, ponto.getId_trajeto());
			em.close();
		} catch (Exception e) {
			System.err.println(e.getMessage());
			u = null;
		} finally {
			em.close();
		}
		return u;
	}

	public LatLng consultaLatLngLogin(LatLng ponto) {
		EntityManager em = factory.createEntityManager();
		LatLng u = new LatLng();
		try {
			u = (LatLng) em
					.createQuery("SELECT u FROM LatLng u WHERE u.login = ?1")
					.setParameter(1, ponto.getId_trajeto()).getSingleResult();
		} catch (Exception e) {
			u = null;
		} finally {
			em.close();
		}
		return u;
	}

	public void destroyFactory() {
		factory.close();
	}

}
